package top.jingles.utils.args;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

public class Parser {
    String title;
    List<Option> options;

    public Parser() {
        title = "";
        options = new ArrayList<Option>();
        options.add(new Option("h", "help", false, "打印本帮助信息", new DealFunction(){
            public boolean Deal(String argValue) {
                PrintHelp();
                return false;
            }
        }));
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public void addOption(Option option) {
        options.add(option);
    }

    public boolean Parse(String[] args) {
        // Create a Parser
        CommandLineParser parser = new DefaultParser();

        // Parse the program arguments
        CommandLine commandLine;
        try {
            commandLine = parser.parse(makeOptions(options), args);
        } catch (ParseException e) {
            System.out.println(e.getMessage());
            return false;
        }

        for (Option opt : options) {
            if (commandLine.hasOption(opt.getOpt())) {
                String argValue = "";
                if (opt.isHasArg()) {
                    argValue = commandLine.getOptionValue(opt.getOpt());
                }
                if (!opt.getDealFunction().Deal(argValue)) {
                    return false;
                }
            }
        }

        return true;
    }

    Options makeOptions(List<Option> opts) {
        Options options = new Options();
        for (Option opt : opts) {
            options.addOption(opt.getOpt(), opt.getLongOpt(), opt.isHasArg(), opt.getDescription());
        }
        return options;
    }

    void PrintHelp() {
        HelpFormatter hf = new HelpFormatter();
        hf.setWidth(110);
        hf.printHelp(title, makeOptions(options), true);
    }
}